package com.example.springrabbitmq.config;

import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
public class RabbitTemplateConfig {
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        return template;
    }

    @Bean
    public RabbitTemplate confirmTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate confirmTemplate = new RabbitTemplate(connectionFactory);
        confirmTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            System.out.println("confirm 方法执行...");
            if (ack) {
                System.out.printf("接收到消息, 消息Id: %s\n", correlationData == null ? null: correlationData.getId());
            } else {
                System.out.printf("未接收到消息, 消息Id: %s\n", correlationData == null ? null: correlationData.getId());
                System.out.println("错误信息：" + cause);
                // 重发等逻辑...
            }
        });
        confirmTemplate.setMandatory(true);
        confirmTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returned) {
                System.out.printf("消息 %s 被退回\n", returned);
            }
        });
        return confirmTemplate;
    }
}
